package com.jokul.web.user;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jokul.model.User;
import com.jokul.service.UserService;
import com.jokul.service.UserServiceImpl;
import com.jokul.utils.MD5;

/**
 * @author: jokul
 * @2013-2-26 下午4:21:52
 */
@WebServlet(
		urlPatterns={"/register.do"},
		initParams={
				@WebInitParam(name = "SUCCESS_VIEW", value = "/pages/user/member.jsp"),
				@WebInitParam(name = "ERROR_VIEW", value = "index.jsp")
		}
)
public class Register extends HttpServlet {

	private static final long serialVersionUID = 1L;
	
	private String SUCCESS_VIEW = null;
	private String ERROR_VIEW = null;

	private UserService userService = new UserServiceImpl();
	
	public void init() throws ServletException {
		SUCCESS_VIEW = getInitParameter("SUCCESS_VIEW");
		ERROR_VIEW = getInitParameter("ERROR_VIEW");
	}
	
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		User user = new User();
		user.setUserName(req.getParameter("userName"));
		user.setPassword(MD5.getMD5(req.getParameter("password")));
		user.setEmail(req.getParameter("email"));
		user.setLastIP(req.getLocalAddr());
		int result = userService.insert(user);
		req.setAttribute("userName", req.getParameter("userName"));
		if(result>0) {
			req.getRequestDispatcher(SUCCESS_VIEW).forward(req, resp);
		}else {
			resp.sendRedirect(ERROR_VIEW);
		}
	}
}
